<?php

namespace app\api\model\service;

use think\Model;
class UserCoupon extends Model
{
    // 表名
    protected $name = 'service_user_coupon';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    public static function checkCoupon($id,$goods)
    {
        $coupon = self::where(['id'=>$id,'state'=>0])->find();
        if(!$coupon)
        {
            return false;
        }
        if(in_array($coupon['type'],[1,3]) && $coupon['goods_id'] != $goods['goods']['id'])
        {
            return false;
        }
        if($coupon['type'] == 2 && $coupon['shop_id'] != $goods['goods']['shop_id'])
        {
            return false;
        }
        return $coupon;
    }

    public static function getCount($params)
    {
        return self::where($params)->count();
    }


    public static function getList($params)
    {
        $list = self::where(['state'=>$params['state'],'user_id'=>$params['user_id']])->field('id,coupon_id,type,goods_id,shop_id,achieve,reduce,exittime,state,createtime')->order('id desc')->page($params['page'])->limit(10)->select();
        foreach ($list as &$value)
        {
            $value['goodsName'] = $value['goods_id']?\app\api\model\service\Goods::where(['id'=>$value['goods_id']])->value('name'):'';
            $value['shopName'] = $value['shop_id']?\app\api\model\service\Shop::getName($value['shop_id']):'';
        }
        return $list;
    }

    public static function getInfo($id)
    {
        return self::where(['id'=>$id])->field('id,achieve,reduce,goods_id,shop_id,type,state,createtime')->find();
    }

}
